package com.atguigu.gmall.payment.interceptors;

import com.atguigu.gmall.payment.pojo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        String username = request.getHeader("username");

        if (userId != null) {
            UserInfo userInfo = new UserInfo(Long.valueOf(userId), null, username);
            THREAD_LOCAL.set(userInfo);
        }
        return true;
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 由于使用的是tomcat线程池，所以请求结束线程并不会结束，如果不手动remove的话，可能引发内存泄漏，最终产生OOM
        THREAD_LOCAL.remove();
    }
}
